package com.example.nbb.Tool;

import com.google.gson.Gson;

import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.util.UUID;

/**
 * 七牛云存储工具类
 *
 */
@Component
public class KoDoTool {
    @Value("${project.qiniuyunkey}") //用途：是从application.yml中获取对应的key值
    private String key;//七牛云的key
    @Value("${project.qiniuyunsecret}") //用途：是从application.yml中获取对应的key值
    private String secret;//七牛云的密码
    @Value("${project.qiniuyunbucket}") //用途：是从application.yml中获取对应的key值
    private String bucket;//七牛云的桶名称
    @Value("${project.qiniuyunbucketurl}") //用途：是从application.yml中获取对应的key值
    private String bucketUrl;//七牛云的桶URL
    private static final Logger logger= LoggerFactory.getLogger(KoDoTool.class);//日志getLogger需要传入的类名

    public void Test(){
        System.out.println(key);
        System.out.println(secret);
        System.out.println(bucket);
        System.out.println(bucketUrl);
        logger.info("Info输出"+key);
        logger.debug("Debug输出"+key);
        logger.warn("Warm输出"+key);
        logger.error("error输出"+key);

    }

    /**
     * 上传文件到七牛云存储
     * @param filePath 本地文件路径
     * @return String 文件在线访问地址
     */
    public String UploadFile(String filePath){
        String fileName= UUID.randomUUID()+"."+filePath.split("\\.")[1];//重新生成文件名
        try{//生成七牛云的配置对象，Configuration需要传入bucket的地域，地域选择错误就会上传失败
            Configuration configuration=new Configuration(Region.huadong());
            UploadManager uploadManager=new UploadManager(configuration);//配置上传对象
            Auth auth= Auth.create(key,secret);//根据七牛云key和secret生成上传token
            String token=auth.uploadToken(bucket);
            Response response= uploadManager.put(filePath,fileName,token);//上传文件并返回结果
            DefaultPutRet putRet= new Gson().fromJson(response.bodyString(),DefaultPutRet.class);//将返回结果解析
            logger.info(putRet.toString());//输出结果
        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return bucketUrl+"/"+fileName;
    }
}
